# -*- coding:utf-8 -*-
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer

from trainword2vec import train_word2vec
from word2vec_test import Word2Vec_Test
import os
import sys
import json
import utils
import requests
import time
from concurrent.futures import ThreadPoolExecutor
import tornado
from tornado.concurrent import run_on_executor
import codecs
import random
import hashlib
import uuid
import scratch_1
from flask import Response
from flask import request
from urllib import parse
from flask import Flask, render_template, send_file, send_from_directory, json, jsonify, make_response
import report_analysis


class IndexHandler(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def initialize(self, word2vec, description_data):
        self.word2vec = word2vec
        self.description_data = description_data

    def get(self):
        self.write("index")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        startTime = time.time()
        # description = utils.getDescription(self.request)
        description = utils.constructDescription1(self.request)
        print("constructDescription time: " + str(time.time() - startTime))
        # sim = yield self.word2vec.cmp_description(sentence, self.description_data)
        sim = yield self.word2vec.sickEstimate(self.request, self.description_data)
        # print("sentence: " + sentence)
        endTime = time.time()
        print("total time cost: " + str(endTime - startTime))
        self.finish({"description": description, "similarity": sim,
                     "procTime": str(endTime - startTime)})


class AddressHandler(RequestHandler):
    def get(self):
        self.write("address get")

    def post(self):
        print("address post")
        jsonbyte = self.request.body
        print('二进制格式ｊｓｏｎ字符串：', jsonbyte)
        jsonstr = jsonbyte.decode('utf8')  # 解码，二进制转为字符串
        print('ｊｓｏｎ字符串：', jsonstr)
        jsonobj = json.loads(jsonstr)  # 将字符串转为json对象

        longitude = jsonobj.get("longitude")
        latitude = jsonobj.get("latitude")

        location = str(latitude) + "," + str(longitude)

        r = requests.get(url='http://api.map.baidu.com/reverse_geocoding/v3/',
                         params={'location': location, 'ak': 'exLGOnGUylFGD7MpuKtUZRL7G4s07I6e', 'output': 'json'})

        result = r.json()
        print("result:")
        print(result)
        city = result['result']['addressComponent']['city']
        print(city)

        self.finish(result)


class TestHandler(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def initialize(self, i, startTime):
        self.i = i
        # print("i: " + str(i))
        self.startTime = startTime
        # print("startTime: " + str(startTime))

    @run_on_executor
    def waitTime(self):
        time.sleep(2)

    def get(self):
        self.write("index")

    @tornado.gen.coroutine
    def post(self):
        # print("startTime: " + str(self.startTime))
        if time.time() - self.startTime > 1:
            self.i = self.i + 1
        # time.sleep(2)
        yield self.waitTime()
        print("time cost: " + str(time.time() - self.startTime))
        self.finish({"i": self.i, "startTime": self.startTime})

# class UploadHandler(RequestHandler):
#     executor = ThreadPoolExecutor(20)

#     def get(self):
#         self.write("upload")

#     @tornado.gen.coroutine
#     # @tornado.web.asynchronous
#     def post(self, *args, **kwargs):
#         #查看上传文件的完整格式，files以字典形式返回
#         #print(self.request.files)
#         filesDict=self.request.files
#         for inputname in filesDict:
#             print("inputname:    "+inputname)
#             #第一层循环取出最外层信息，即input标签传回的name值
#             #用过filename键值对对应，取出对应的上传文件的真实属性
#             http_file=filesDict[inputname]
#             for fileObj in http_file:
#                 #第二层循环取出完整的对象
#                 #取得当前路径下的upfiles文件夹+上fileObj.filename属性(即真实文件名)
#                 filePath=os.path.join(os.path.dirname(__file__),fileObj.filename)
#                 print("filePath:"+filePath)
#                 suffix = os.path.splitext(filePath)[-1]
#                 print("suffix:=============-----------"+suffix)
#                 imageFormatList = ['.bmp','.png','.gif','.jpeg','.jpg','.mng','.tiff','.tif']
#                 videoFormatList = ['.wmv','.asf','.asx','.rm','.rmvb','.mp4','.3gp','.mov','.m4v','.avi','.dat']
#                 if suffix in imageFormatList :
#                     print("这个是图片文件")
#                     randomNum=random.randint(0,30)
#                     self.finish({"randomNum": randomNum})
#                 elif suffix in videoFormatList :
#                     print("这个是视频文件")
#                     #心率
#                     heartRate=random.randint(60,100)
#                     #呼吸率
#                     respiratoryRate=random.randint(16,20)
#                     #收缩压
#                     systolicPressure=random.randint(90,140)
#                     #舒张压
#                     diastolicPressure=random.randint(60,90)
#                     self.finish({"heartRate": heartRate,"respiratoryRate":respiratoryRate
#                     ,"systolicPressure":systolicPressure,"diastolicPressure":diastolicPressure})
#                 else :
#                     print("不清楚是什么文件")
#                 with open(filePath,'wb') as f:
#                      f.write(fileObj.body)
#         self.write('上传成功')
#         self.finish()


class UploadImageHandler(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        self.write("uploadImage")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        # 查看上传文件的完整格式，files以字典形式返回
        # print(self.request.files)
        filesDict = self.request.files
        for inputname in filesDict:
            print("uploadImage: "+inputname)
            # 第一层循环取出最外层信息，即input标签传回的name值
            # 用过filename键值对对应，取出对应的上传文件的真实属性
            http_file = filesDict[inputname]
            for fileObj in http_file:
                # 第二层循环取出完整的对象
                # 取得当前路径下的upfiles文件夹+上fileObj.filename属性(即真实文件名)
                # filePath = os.path.join(os.path.dirname(
                #     __file__), "medium", fileObj.filename)
                # with open(filePath, 'wb') as f:
                #     f.write(fileObj.body)
                fileObjStr = str(fileObj.body).encode()
                s = hashlib.sha256()    # Get the hash algorithm.
                s.update(fileObjStr)    # Hash the data.
                imageFileHashValue = s.hexdigest()       # Get he hash value.
                print ("imageFileHashValue:"+imageFileHashValue)
        imgDescription, similarity = utils.imgConstructDescription(
            imageFileHashValue)
        self.finish({"imgDescription": imgDescription,
                     "imgSimilarity": similarity})


class UploadVideoHandler(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        self.write("uploadVideo")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        filesDict = self.request.files
        for inputname in filesDict:
            print("uploadVideo: "+inputname)
            http_file = filesDict[inputname]
            for fileObj in http_file:
                # filePath = os.path.join(os.path.dirname(
                #     __file__), "medium", fileObj.filename)
                # with open(filePath, 'wb') as f:
                #     f.write(fileObj.body)
                fileObjStr = str(fileObj.body).encode()
                s = hashlib.sha256()    # Get the hash algorithm.
                s.update(fileObjStr)    # Hash the data.
                videoFileHashValue = s.hexdigest()       # Get he hash value.
                print ("videoFileHashValue:"+videoFileHashValue)
        videoDescription, similarity = utils.videoConstructDescription(
            videoFileHashValue)
        self.finish({"videoDescription": videoDescription,
                     "videoSimilarity": similarity})


class UploadImageHandler1(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        self.write("uploadImage")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        # 查看上传文件的完整格式，files以字典形式返回
        # print(self.request.files)
        filesDict = self.request.files
        for inputname in filesDict:
            print("uploadImage: "+inputname)
            # 第一层循环取出最外层信息，即input标签传回的name值
            # 用过filename键值对对应，取出对应的上传文件的真实属性
            http_file = filesDict[inputname]
            for fileObj in http_file:
                # 第二层循环取出完整的对象
                # 取得当前路径下的upfiles文件夹+上fileObj.filename属性(即真实文件名)
                filePath = os.path.join(os.path.dirname(
                    __file__), "medium", fileObj.filename)
                with open(filePath, 'wb') as f:
                    f.write(fileObj.body)

            returnJson = scratch_1.demo(filePath)
            print("returnJson1: "+str(returnJson))
            print("filePath1: "+filePath)
            # os.remove(filePath)
        # self.finish({"filePath1": filePath,"imageByte":str(returnJson)})
        self.finish(returnJson)


class UploadImageHandler2(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        self.write("uploadImage")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        # 查看上传文件的完整格式，files以字典形式返回
        # print(self.request.files)
        filesDict = self.request.files
        for inputname in filesDict:
            print("uploadImage: "+inputname)
            # 第一层循环取出最外层信息，即input标签传回的name值
            # 用过filename键值对对应，取出对应的上传文件的真实属性
            http_file = filesDict[inputname]
            for fileObj in http_file:
                # 第二层循环取出完整的对象
                # 取得当前路径下的upfiles文件夹+上fileObj.filename属性(即真实文件名)
                filePath = os.path.join(os.path.dirname(
                    __file__), "medium", fileObj.filename)
                with open(filePath, 'wb') as f:
                    f.write(fileObj.body)
            returnJson = scratch_1.demo(filePath)
            print("returnJson2: "+str(returnJson))
            print("filePath2:"+filePath)
            # os.remove(filePath)
        self.finish(returnJson)


class UploadImageHandler3(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        self.write("uploadImage")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        # 查看上传文件的完整格式，files以字典形式返回
        # print(self.request.files)
        filesDict = self.request.files
        for inputname in filesDict:
            print("uploadImage: "+inputname)
            # 第一层循环取出最外层信息，即input标签传回的name值
            # 用过filename键值对对应，取出对应的上传文件的真实属性
            http_file = filesDict[inputname]
            for fileObj in http_file:
                # 第二层循环取出完整的对象
                # 取得当前路径下的upfiles文件夹+上fileObj.filename属性(即真实文件名)
                filePath = os.path.join(os.path.dirname(
                    __file__), "medium", fileObj.filename)
                with open(filePath, 'wb') as f:
                    f.write(fileObj.body)
            returnJson = scratch_1.demo(filePath)
            print("returnJson3: "+str(returnJson))
            print("filePath3:"+filePath)
            # os.remove(filePath)
        self.finish(returnJson)


class DownloadExcelFile(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        filePath = self.get_query_argument('filePath')
        if filePath is None:
            print("请输入参数")
        else:
            if filePath == '':
                print("请输入正确路径")
            else:
                if not os.path.isfile(filePath):
                    print(filePath)
                    print("文件路径不存在")
                else:
                    print("文件路径不存在1111")
                    fileName = os.path.basename(filePath)
                    print(fileName)
                    # response = FileResponse(scratch_1.file_iterator(filePath))
                    # print("文件路径不存在2222")
                    # response['Content-Type'] = 'application/txt'
                    # response['Content-Disposition'] = 'attachment;filename="{}"'.format(escape_uri_path(fileName))
                    # return response
                    # response = send_file(filePath,attachment_filename=fileName)
                    # return response
                    # Content-Type这里我写的时候是固定的,也可以根据实际情况传值进来
                    self.set_header('Content-Type', 'application/x-xls')
                    self.set_header('Content-Disposition',
                                    'attachment;filename={}'.format(fileName))
                    # 读取的模式需要根据实际情况进行修改
                    with open(filePath, 'rb') as f:
                        data = f.read()
                        print(data)
                        self.write(data)
                    self.finish()

    # @tornado.gen.coroutine
    # def post(self, *args, **kwargs):
    #     # 查看上传文件的完整格式，files以字典形式返回
    #     # print(self.request.files)
    #     filePath = self.request.values.get("filePath")
    #     if filePath is None:
    #         print("请输入参数")
    #     else:
    #         if filePath == '':
    #             print("请输入正确路径")
    #         else:
    #             if not os.path.isfile(filePath):
    #                 print("文件路径不存在")
    #             else:
    #                 fileName = os.path.basename(filePath)
    #                 response = Response(scratch_1.file_iterator(filePath))
    #                 response.headers['Content-Type'] = 'application/octet-stream'
    #                 response.headers["Content-Disposition"] = 'attachment;filename="{}"'.format(fileName)
    #                 return response


class ReturnRadarImageStr(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        self.write("returnImageStr")

    @tornado.gen.coroutine
    def post(self, *args, **kwargs):
        # 查看上传文件的完整格式，files以字典形式返回
        # print(self.request.files)
        xlsxFilePath1 = self.get_body_argument("xlsxFilePath1")
        xlsxFilePath2 = self.get_body_argument("xlsxFilePath2")
        xlsxFilePath3 = self.get_body_argument("xlsxFilePath3")
        print("xlsxFilePath1:"+xlsxFilePath1+",xlsxFilePath2:" +
              xlsxFilePath2+",xlsxFilePath3:"+xlsxFilePath3)
        excelPathJson = {}
        excelPathJson['dataAll'] = xlsxFilePath1
        excelPathJson['dataL'] = xlsxFilePath2
        excelPathJson['dataX'] = xlsxFilePath3
        pngPath = report_analysis.demo(excelPathJson)
        print(pngPath)
        print("aaaaaaaa1111111111222222222222222222233333333333")
        self.finish(pngPath)
        # os.remove(xlsxFilePath1)
        # os.remove(xlsxFilePath2)
        # os.remove(xlsxFilePath3)


class DownloadRadarImageFile(RequestHandler):
    executor = ThreadPoolExecutor(20)

    def get(self):
        filePath = self.get_query_argument('filePath')
        if filePath is None:
            print("请输入参数")
        else:
            if filePath == '':
                print("请输入正确路径")
            else:
                if not os.path.isfile(filePath):
                    print(filePath)
                    print("文件路径不存在")
                else:
                    print("文件路径不存在1111")
                    fileName = os.path.basename(filePath)
                    print(fileName)
                    # Content-Type这里我写的时候是固定的,也可以根据实际情况传值进来
                    self.set_header('Content-Type', 'application/octet-stream')
                    self.set_header('Content-Disposition',
                                    'attachment;filename={}'.format(fileName))
                    # 读取的模式需要根据实际情况进行修改
                    with open(filePath, 'rb') as f:
                        data = f.read()
                        print(data)
                        self.write(data)
                    self.finish()
                    # os.remove(filePath)


if __name__ == '__main__':
    output_model_name = "models/65d/models/word2vec_128d_model_zonghe"
    word2vec = Word2Vec_Test(output_model_name)

    description_file = 'data/test_data/description.txt'
    description = codecs.open(description_file, 'r', 'utf-8')
    description_data = description.readlines()

    startTime = time.time()

    i = 0
    app = Application(
        [(r'/', IndexHandler, {"word2vec": word2vec, "description_data": description_data}),
         (r'/address/', AddressHandler), (r'/test/',
                                          TestHandler, {'i': i, "startTime": startTime}),
         (r'/uploadImage', UploadImageHandler), (r'/uploadVideo', UploadVideoHandler),
         (r'/uploadImage1', UploadImageHandler1), (r'/uploadImage2', UploadImageHandler2),
         (r'/uploadImage3', UploadImageHandler3), (r'/downloadExcelFile', DownloadExcelFile),
         (r'/returnRadarImageStr', ReturnRadarImageStr), (r'/downloadRadarImageFile', DownloadRadarImageFile)])
    http_server = HTTPServer(app, max_buffer_size=504857600)
    # 最原始的方式
    http_server.bind(8888)
    http_server.start(0)

    # 启动Ioloop轮循监听
    IOLoop.current().start()
    print("listening 8888")
